#!/usr/bin/python

import os, sys
from optparse import OptionParser
from mako.template import Template
import gen_view_info, gen_zone_file
def main(opts):
    makotext = '''
options {
        directory \"${opts["conf"]}\";
        pid-file "${opts["conf"]}/etc/named.pid";
        recursion no;
        allow-new-zones yes;
        % for server in opts['svr'].split(','):
        listen-on port ${server.split(':')[1]} { ${server.split(':')[0]}; };
        % endfor
        % if len(viewlist) == 0:
        allow-update { any; };
        % endif
};
% if len(viewlist) == 0:
    % for zonename in zonelist:
zone \"${zonename}\" {
    type master;
    file \"${opts["conf"]}/data/${zonename}txt\";
};
    % endfor
% else:
   % if opts['client'] != 'None':
	<% ipinfo = opts['client'].split('.') %>
acl \"match\"{
	% for i in range(256):
		${ipinfo[1]}.${ipinfo[0]}.${i}.0/24;
	% endfor
		${opts['client']}/32;
};
		
acl \"nomatch\"{
	% for i in range(130):
		% if int(ipinfo[0]) != i:
		% for j in range(2):
			${i}.${j}.${i}.0/24;
		% endfor
		% endif
	% endfor
};
   % else:
acl \"match\"{
        any;
};
key key1 {
        algorithm hmac-md5;
        secret "JybkdnSoWYpoHLeF423QPQ==";
};
   % endif
    % for  viewname in viewlist:
view \"${viewname}\" {    
    % if viewlist.index(viewname)== len(viewlist)-1:
        match-clients { \"match\"; };
    %else:
        match-clients { \"nomatch\"; };
    % endif
        % for zonename in zonelist:
          zone \"${zonename}\" {
              type master;
              file \"${opts["conf"]}/data/${viewname}/${zonename}txt\";
              % if opts['client'] == 'None':
              allow-query {key key1; };
              % endif
           };
        % endfor
    
};  
    % endfor 
%endif
% if 'log' in opts and opts['log'] == "yes":
logging {
    channel query_log {
        file \"${opts['conf']}/log/query.log\" versions 5 size 10m;
        print-category yes;
        print-severity yes;
        print-time yes;
        severity info;
    };
    channel queryerrors_log {
        file \"${opts['conf']}/log/queryerrors.log\" versions 5 size 10m;
        print-category yes;
        print-severity yes;
        print-time yes;
        severity debug 3;
    };
    channel default_log {
        file \"${opts['conf']}/log/default.log\" versions 5 size 10m;
        print-category yes;
        print-severity yes;
        print-time yes;
        severity info;
    };
    channel general_log {
        file \"${opts['conf']}/log/general.log\" versions 5 size 10m;
        print-category yes;
        print-severity yes;
        print-time yes;
        severity info;
    };
    channel update_log {
        file \"${opts['conf']}/log/update.log\" versions 5 size 10m;
        print-category yes;
        print-severity yes;
        print-time yes;
        severity info;
    };
    channel xferout_log {
        file \"${opts['conf']}/log/xferout.log\" versions 5 size 10m;
        print-category yes;
        print-severity yes;
        print-time yes;
        severity debug 10;
    };
    channel client_log {
        file \"${opts['conf']}/log/client.log\" versions 5 size 10m;
        print-category yes;
        print-severity yes;
        print-time yes;
        severity debug 1;
    };
    category queries { query_log; };
    category query-errors { queryerrors_log; };
    category general { general_log; };
    category default { default_log; };
    category update { update_log; };
    category xfer-out { xferout_log; };
    category client { client_log; };
};
%endif
'''
    if 'zonenum' not in opts:
        opts['zonenum'] = 0
    if 'viewnum' not in opts:
        opts['viewnum'] = 0
    if 'zoneprefix' not in opts:
        opts['zoneprefix'] = 'zone'
    if 'viewprefix' not in opts:
        opts['viewprefix'] = 'view'

    zonelist = gen_zone_file.gen_rand_zone(opts['zonenum'], opts['zoneprefix'])
    ''' edit start by lyn '''
    viewlist = gen_view_info.gen_rand_view(opts['viewnum'], opts['viewprefix'])
    ''' edit end by lyn ''' 
    tpl = Template(makotext) 
    txt = tpl.render(opts = opts, viewlist = viewlist, zonelist = zonelist)
    
    try:
       os.mkdir(opts["conf"] + '/etc')
       os.mkdir(opts["conf"] + '/data')
       os.mkdir(opts["conf"] + '/log')
    except OSError:
       pass

    with open(opts["conf"] + '/etc/named.conf', "w") as fp:
        fp.write(txt)

def getopt():
    """
    get options from user.
    """
    usage = "usage: %prog [options]"
    parser = OptionParser(usage)
    parser.add_option("-c", "--confpath", dest="conf",
        help="specify local config file's full path")
    parser.add_option("-s", "--server", dest="svr", default = "0.0.0.0:53",
        help="specify listening address , default is listen on all interface")
    parser.add_option("-v", "--viewnum", dest="viewnum", default=0, type = int,
        help="specify the view list file name")
    parser.add_option("-n", "--zonenum", dest="zonenum", default=1, type=int,
        help="specify the view list file name")
    parser.add_option("-l", "--log", dest="log", default = None,
        help="specify the log")
    parser.add_option("-t", "--client", dest="client", default = '127.0.0.1',
        help="specify the client IP ")

    (opts, args) = parser.parse_args()

    if(opts.conf == None):
        parser.print_help()
        sys.exit(1)

    return opts

if __name__ == "__main__":
    opts = getopt()
    main(vars(opts))
